package com.itbaizhan.openhis.service.impl;



import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itbaizhan.openhis.config.SmsConfig;
import com.itbaizhan.openhis.domain.VerificationCode;
import com.itbaizhan.openhis.service.VerificationCodeService;
import com.itbaizhan.openhis.mapper.VerificationCodeMapper;
import com.itbaizhan.openhis.utils.HttpUtils;
import com.itbaizhan.openhis.utils.IdGeneratorSnowflake;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URLEncoder;

/**
 *
 */
//因为是远程调用，是用第三方平台，如果响应时间长，dubbo默认是重试三次，那会造成三调用，用户手机上会收到三条信息
//限制发送次数，就不会给用户造成不好的体验，在@Service后加(timeout = 5000,methods = {@Method(name = "sendSms",retries = 0)})
@Service(timeout = 5000,methods = {@Method(name = "sendSms",retries = 0)})//改为dubbo的service,要远程调用
public class VerificationCodeServiceImpl extends ServiceImpl<VerificationCodeMapper, VerificationCode>
    implements VerificationCodeService{

    @Autowired
    private VerificationCodeMapper verificationCodeMapper; //用于保存验证码

    @Autowired
    private SmsConfig smsConfig;



    /**
     * 发送短信
     * @param phoneNumber
     * @return
     */
    @Override
    public int sendSms(String phoneNumber) {
        //生成四位验证码
        Integer code = IdGeneratorSnowflake.generateVerificationCode();
       try {
           //组装方法的参数与接口
           String result = this.execute(phoneNumber,code);
           //转为JSON
           JSONObject jsonObject = (JSONObject) JSON.parse(result);
           if (jsonObject != null && StringUtils.isNotEmpty(jsonObject.getString("respCode"))) {
               //发送成功后，平台返回0000
               if (jsonObject.getString("respCode").equals("0000")) {
                   return saveVerification(phoneNumber, code); //保存
               }
           }
       } catch (Exception e){
           e.printStackTrace();
       }
        return -1; //发送失败返回-1
    }



    /**
     * 发送成功后把验证码保存到时his_verification_code表
     * @param phoneNumber
     * @param code
     * @return
     */
    private int saveVerification(String phoneNumber, Integer code) {
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setPhoneNumber(phoneNumber);
        verificationCode.setVerificationCode(code);
        verificationCode.setCreateTime(DateUtil.date());
        verificationCode.setIsCheck(0);
        return  verificationCodeMapper.insert(verificationCode);
    }

    /**
     * 短信发送
     * @return
     *  https://openapi.danmi.com/distributor/sendSMS
     */
    private String execute(String phoneNumber,Integer code) throws Exception{
        StringBuffer sb = new StringBuffer();
        sb.append("accountSid").append("=").append(smsConfig.getACCOUNT_SID());
        sb.append("&to").append("=").append(phoneNumber);
        sb.append("tremplateid").append("=").append(smsConfig.getTEMPLATE_ID());
        sb.append("&param").append("=").append(URLEncoder.encode(code.toString(),"UTF-8"));
        String body = sb.toString()+smsConfig.createCommonParam(smsConfig.getACCOUNT_SID(),smsConfig.getAUTH_TOKEN());
        return HttpUtils.post(smsConfig.getBASE_URL(),body);

    }


    //校验验证码
    // 在Verification_code 表中查到电话号码，验证码说明这是有效的
    @Override
    public VerificationCode checkCode(String phoneNumber, Integer code) {
        QueryWrapper<VerificationCode> wrapper = new QueryWrapper<>();
        wrapper.eq(VerificationCode.PHONE_NUMBER,phoneNumber);
        wrapper.eq(VerificationCode.VERIFICATION_CODE,code);
        wrapper.eq(VerificationCode.IS_CHECK,0);


        return verificationCodeMapper.selectOne(wrapper);
    }
}




